package com.yhx.security.changyou;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
public class Encryption {
    //private static final String VI="1234567812345678";
    public static void main(String args[]) throws Exception {
        System.out.println(decryptByAes("xBaGoJkCwahQV/O7E6rNAE4BywqCx3Uqv6lmNeOt7sY7o+lNPHK1fkX/RZAf112jfjYyTzpMeJkj6uT1wR+L88U/n7DM8RMBTp4hZsiiHUw=","IQcoqkGu9Jo2vAB1","1234567812345678"));
        String encryptData=encryptByAes("111","123456789qwertyh","1234567812345678");
        System.out.println(encryptData);
        System.out.println(decryptByAes(encryptData,"123456789qwertyh","1234567812345678"));
    }
    /**
     * 加密
     * @return
     * @throws Exception
     */
    public static String encryptByAes(String data,String key,String iv) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AESUtil/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength
                        + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AESUtil");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new sun.misc.BASE64Encoder().encode(encrypted);
        } catch (Exception e) {

        }
        return null;
    }
    /**
     * 解密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptByAes(String data,String key,String iv) throws Exception {
        try {
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
            Cipher cipher = Cipher.getInstance("AESUtil/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AESUtil");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {

        }
        return null;
    }
}
